#include <stdio.h>
#include <stdlib.h>
#include <libspe2.h>
#include <pthread.h>

#define SPE_NUM 9

void* run_context(void*);

int main( int argc, char** argv )
{
  int ret;
  
  srand48(0);

  spe_context_ptr_t spe[SPE_NUM];
  spe_program_handle_t *prog;
  int i;
  pthread_t threads[SPE_NUM];

  //printf("%f\n", drand48());

  prog = spe_image_open("hello_spe.elf");

  for( i = 0; i<SPE_NUM; i++ ) {
    spe[i] = spe_context_create(0, NULL);
    ret = spe_program_load(spe[i], prog);
  }
  
  for( i = 0; i<SPE_NUM; i++ ) {
    pthread_create( &threads[i], NULL, run_context, &spe[i] );
  }

  for( i = 0; i<SPE_NUM; i++ ) {
    pthread_join( threads[i], NULL );
  }

  //if( !spe[7] ) {
  //  perror("spe_context_create");
  //  exit(1);
  //}

  for( i = 0; i<SPE_NUM; i++ ) {
     ret = spe_context_destroy(spe[i]);
  }
  
  ret = spe_image_close(prog);

  return 0;
}

void* run_context(void* thread_args)
{
  int ret;
  unsigned int entry = SPE_DEFAULT_ENTRY;
  spe_stop_info_t stop_info;
  spe_context_ptr_t* spe_ptr = (spe_context_ptr_t*)thread_args;

  ret = spe_context_run( *spe_ptr, &entry, 0, NULL, NULL, &stop_info);

  return NULL;
}
